<?php

class yumi {

    public $var_talk;
    public $conf, $rest_uri;
    public $yuming_website, $yuming_id, $yuming_name;
    public $mobile_url, $web_url;

    public function __construct() {
        $cachefile = DATA . '/cache/config_cache.inc.php';
        if (!is_file($cachefile)) {
            config::update_config();
        }
        $this->conf = require $cachefile;
        $this->conf['ftime'] = filemtime($cachefile);

        $GLOBALS['G'] = $this->conf;

        $uri_info = parse_url($_SERVER['REQUEST_URI']);
        $this->rest_uri = trim($uri_info['path'], '/');
        $httpname = $_SERVER['HTTP_HOST'];

        if (preg_match("#^www\.#", $httpname)) {
            $httpname = substr($httpname, 4);
        }
        if (is_mobile() && IS_MOBILE_SITE) {
            define('IS_MOBILE_SITE', true);
            $this->mobile_url = $this->web_url;
        }

//        if (preg_match("#^m\.#", $httpname)) {
//            define('IS_MOBILE_SITE', true);
//            $httpname = substr($httpname, 2);
//        } else {
//            $mobilename = "m." . $httpname;
//            $this->mobile_url = 'http://' . $mobilename . $_SERVER['REQUEST_URI'];
//        }

        $this->yuming_website = db::find("select * from yuming where name='www.{$httpname}' OR name='{$httpname}'");


        if (!defined('APPNAME') && M != 'catch') {
            if (empty($this->yuming_website)) {
                throw new Exception("Error:没有绑定域名,请登录后台设置");
                exit;
            }

            $GLOBALS['W'] = $this->yuming_website;

            define('IS_MOBILE_SITE_OPEN', $GLOBALS['W']['mobileSwitch'] == 1);

            $this->yuming_id = $this->yuming_website['id'];
            $this->yuming_name = $this->yuming_website['name'];
            $this->web_url = 'http://' . $this->yuming_website['name'] . $_SERVER['REQUEST_URI'];
        }

        // 系统测试
        if ($this->rest_uri == 'systest') {
            echo 'success';
            exit;
        }

        //推送
//        if (!empty($GLOBALS['G']['baidu_tui_token']) && rand(0, 20) == 0) {
//            $ping = new ping_RPC();
//            $result = $ping->ping();
//        }
    }

    public static function baidu_push($yumingid = 0, $limit = 100) {
        $ping = new ping_RPC();
        $result = $ping->ping($yumingid, $limit);
    }
    
    public static function baidu_push_jsc_url($yumingid,$urls) {
        $ping = new ping_RPC();
        $result = $ping->push_url($yumingid, $urls);
        return $result;
    }

    public static function curlpost($url, $post_data = array(), $signkey = '', $cookiefile = '') {
        $post_data['version'] = $GLOBALS['G']['softversion'];
        return httpUnit::post($url, $post_data, $signkey, $cookiefile);
    }

    

    public static function convert_images_url_path($url, $link = '', $yuming_id = '') {
        if ($link) {
            $url = htmlHelper::fix_path($link, $url);
        }
        $img_ext = pathinfo($url, PATHINFO_EXTENSION);
        $md5 = md5($url);
        $md51 = substr($md5, 0, 2);
        $md52 = substr($md5, 2, 2);
        $md53 = substr($md5, 10, 16);
        $hash = $md51 . $md52 . $md53;
        if (in_array($img_ext, array('jpg', 'jpeg', 'png', 'gif'))) {
            $img_ext = "." . $img_ext;
        } elseif ($img_ext == '') {
            $img_ext = ".img";
        } else {
            return "";
        }

        if ($yuming_id) {
            $str_img = "/uploads/{$yuming_id}/" . $md51 . "/" . $md52 . "/" . $md53 . $img_ext;
        } else {
            $str_img = "/uploads/attachment/" . $md51 . "/" . $md52 . "/" . $md53 . $img_ext;
        }

        if (!is_file(ROOT . $str_img)) {
            $imgcon = db::find("select * from attachment where hash='$hash'");
            if (empty($imgcon)) {
                $now_time = time();
                db::query("insert into attachment (hash,url,addtime)
					values ('$hash','$url','$now_time')");
            }
        }
        return $str_img;
    }

    //转换文章内图片地址
    public static function convert_images_patch($body, $alt = '', $link = '', $yuming_id = '') {
        $GLOBALS['catchlink'] = $link;
        $GLOBALS['img_ym_id'] = $yuming_id;
        $body = preg_replace_callback('/src=\"(.*?)\"/is', function($data) {
            $str_img = yumi::convert_images_url_path($data[1], $GLOBALS['catchlink'], $GLOBALS['img_ym_id']);
            if ($GLOBALS['G']['downPicture'] == 1) {
                if ($str_img) {
                    return "src={$str_img}";
                } else {
                    return "";
                }
            } elseif ($GLOBALS['G']['downPicture'] == 2) {
                return "src=$data[1]";
            } else {
                return "";
            }
        }, $body);
        $body = str_replace('@img#alt@', $alt, $body);
        return $body;
    }

    //接受数组参数
    //同义词替换
    public static function replace_word($body, $yuming_id) {
        $list_rword = db::select("select * from reword where yuming_id='$yuming_id' or yuming_id=0");

        $GLOBALS['protecttag'] = array();
        $body = preg_replace_callback('#<a.*?>.*?</a>|<img.*?>|\[img\].*?\[/img\]|\[url\].*?\[/url\]#is', function($data) {
            $key = substr(md5($data[0]), 10, 16);
            $GLOBALS['protecttag'][$key] = $data[0];
            return '~' . $key . '~';
        }, $body);

        #inline-ignore
        $body = replace_word($list_rword, $body);
        //释放保护
        $body = preg_replace_callback('#~([a-z0-9]{16})~#is', function($data) {
            if (isset($GLOBALS['protecttag'][$data[1]])) {
                return $GLOBALS['protecttag'][$data[1]];
            }
            return $data[0];
        }, $body);
        return $body;
    }

    //关键词优化
    public static function seoword($body, $yuming_id,$words) {
        //print_r($body);
        $r = db::find("select * from seoconfig where yuming_id='$yuming_id'");
        //未设置优化
        if (!$r) {
            return $body;
        }
        $r['seoWordNum'] = intval($r['seoWordNum']);
        //未开启
        if (empty($words) || !$r['seoWordNum']) {
            return $body;
        }
        
        //伪原创比例
        $ys = crypt::from62(substr(md5($body['title']), 0, 3)) % 100;
        $seoWordScale = intval($r['seoWordScale']);
        if ($seoWordScale < $ys) {
            return $body;
        }
        //取出词语
//        $sw_arr = str_replace(array(',', '，'), "\n", $r['seoWord']);
//        $sw_arr = explode("\n", $sw_arr);
//        foreach ($sw_arr as $k => $value) {
//            $sw_arr[$k] = trim($value);
//        }
        $sw_arr = array_filter($words);
        $idx = mt_rand(0, max(0, count($sw_arr) - $r['seoWordNum']));
        $sw_arr = array_slice($sw_arr, $idx, $r['seoWordNum']);
        $seowords = addslashes(join(',', $sw_arr));
        if (!empty($sw_arr)) {
            //插入文章
            $sw_arr_num = count($sw_arr);
            $body_array = explode('，', $body['body']);
            $body_s_count = count($body_array);
            $snum = ceil(($body_s_count / 2) / $sw_arr_num);
            //echo "<br/>";
            #inline-ignore
            foreach ($sw_arr as $key => $value) {
                $k = $snum * $key + 1;
                if (isset($body_array[$k])) {
                    $body_array[$k] = $value . $body_array[$k];
                }
            }
            $body['body'] = join("，", $body_array);
            //插入标题
            if ($r['seoTitle'] == '1') {
                if ($r['seoTitlex'] == '1') {
                    $body['title'] = strip_tags($sw_arr[0]) . $body['title'];
                } elseif ($r['seoTitlex'] == '2') {
                    $body['title'] = $body['title'] . strip_tags($sw_arr[0]);
                } elseif ($r['seoTitlex'] == '3') {
                    $tlen = mb_strlen($body['title'], 'utf-8');
                    $blen = mb_strlen($body['body'], 'utf-8');
                    $sp = $blen % $tlen;
                    $body['title'] = mb_substr($body['title'], 0, $sp, 'utf-8') . strip_tags($sw_arr[0]) . mb_substr($body['title'], $sp, $tlen - $sp, 'utf-8');
                }
            }
            $body['sw_arr'] = $sw_arr;
        }
        return $body;
    }
    
    //关键词和标签优化
    public static function autokeywords($seod,$yuming_id,$arr_words) {
        //print_r($body);
        $r = db::find("select * from seoconfig where yuming_id='$yuming_id'");
        //未设置优化
        if (!$r) {
            return null;
        }
        $has_words = [];
        if(!empty($seod['sw_arr'])) {
            $has_words = $seod['sw_arr']; //必须要的
        }
        $keywords_arr = [];
        $tags_arr = [];
        $keyword_num = intval($r['autokeywords']);
        $tags_num = intval($r['autotags']);
        if(!empty($keyword_num)) {
            if($keyword_num <= count($has_words)) { //如果足够
                $has_words =  array_slice($has_words, 0, $keyword_num);
            }else {
                foreach($arr_words as $v) {
                    if(!in_array($v,$has_words)) {
                        $has_words[] = $v;
                    }
                    if(count($has_words)>=$keyword_num) {
                        break;
                    }
                }
            }
        }else {
            $has_words = [];
        }
        $result['keyword'] = implode('，',$has_words);
        $result['tags']= [];
        if(!empty($tags_num)) {
            if($tags_num <= count($has_words)) { //如果足够
                $has_words =  array_slice($has_words, 0, $tags_num);
            }else {
                foreach($arr_words as $v) {
                    if(!in_array($v,$has_words)) {
                        $has_words[] = $v;
                    }
                    if(count($has_words)>=$tags_num) {
                        break;
                    }
                }
            }
            $result['tags'] = $has_words;
        }
        return $result;
    }

            // 标题自动优化
    public static function autoseo($title, $yuming_id) {
        $r = db::find("select * from seoconfig where yuming_id='$yuming_id'");
        if (!$r || $r['autoseo'] == 0) {
            return '';
        }
        if ($r['autonum'] > 5 || $r['autonum'] <= 0) {
            $r['autonum'] = 5;
        }

        $title = urlencode($title);
        $data = "";

        $url = "http://tuijian.sogou.com/websearch/features/sohu_recommend.jsp";
        $postdata = "title={$title}&content=1&url=http://sports.sohu.com/20170427/n490895141.shtml";

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
        $output = curl_exec($ch);
        curl_close($ch);

        $output = urldecode($output);
        $kw = json_decode($output, true);

        if (!empty($kw['hotwords'])) {
            $kw['hotwords'] = array_slice($kw['hotwords'], 0, $r['autonum']);
            $word = addslashes(implode('_', $kw['hotwords']));
        }
        //dump($word);
        return $word;
    }

    public static function encrypt($data) {
        srand((double) microtime() * 1000000);
        $rand = md5(rand(0, 32000));
        $ctr = 0;
        $tmp = '';
        for ($i = 0; $i < strlen($data); $i++) {
            $ctr = $ctr == strlen($rand) ? 0 : $ctr;
            $tmp .= $rand[$ctr] . ($data[$i] ^ $rand[$ctr++]);
        }
        return rtrim(base64_encode(yumi::proc($tmp)), '=');
    }

    public static function decrypt($data) {
        $data = yumi::proc(base64_decode($data));
        $tmp = '';
        for ($i = 0; $i < strlen($data); $i++) {
            $tmp .= $data[$i] ^ $data[++$i];
        }
        return $tmp;
    }

    protected static function proc($data) {
        $auth_num_key = '!roBva*hcks9';
        if (empty($auth_num_key)) {
            exit('auth_num_key does not exists!');
        }
        $ctr = 0;
        $tmp = '';
        for ($i = 0; $i < strlen($data); $i++) {
            $ctr = $ctr == strlen($auth_num_key) ? 0 : $ctr;
            $tmp .= $data[$i] ^ $auth_num_key[$ctr++];
        }
        return $tmp;
    }
    

    //随机得到关键词库中的几个关键词
    public static function get_words_lists($num, $yuming_id) {
        $table = "words_{$yuming_id}";
        if(!db::table_exist($table)) {
            $table = "words";
        }
        $data = db::select("SELECT * FROM `{$table}` AS t1 JOIN (SELECT ROUND(RAND() * (
            (SELECT MAX(id) FROM `{$table}`)-(SELECT MIN(id) FROM `{$table}`))+(SELECT MIN(id) FROM `{$table}`)) AS id) AS t2
            WHERE t1.id >= t2.id
            ORDER BY t1.id LIMIT {$num};"
        );
        $result = [];
        foreach($data as $v) {
            $result[] = $v['title'];
        }
        return $result;
    }
    
    //随机得到标签库
    public static function get_tags_lists($num, $yuming_id) {
        $data = db::select("SELECT * FROM `tagslist_{$yuming_id}` AS t1 JOIN (SELECT ROUND(RAND() * (
            (SELECT MAX(id) FROM `tagslist_{$yuming_id}`)-(SELECT MIN(id) FROM `tagslist_{$yuming_id}`))+(SELECT MIN(id) FROM `tagslist_{$yuming_id}`)) AS id) AS t2
            WHERE t1.id >= t2.id
            ORDER BY t1.id LIMIT {$num};"
        );
        $result = [];
        foreach($data as $v) {
            $result[] = $v['tagsname'];
        }
        return $result;
    }

}

//处理织梦标签
class dede {

    //处理dedecms标签
    public static function dedehandle($string = '') {

        $dede_rules = array(
            '/\{dede\:php\s*\}(.+?)\{\/dede\:php\s*\}/is' => array('_dede_php', 1),
            '/\[field\:[\w]+ name=[\'\"]?(\w+)[\'\"]?[^\]]+runphp[^\]]+\](.+?)\[\/field\:[\w]+\]/is' => array('_dede_php', -1),
            '/\[field\:([\.\w]+)[^\]]+runphp[^\]]+\](.+?)\[\/field\:(\\1)\]/is' => array('_dede_php', -1),
            '/\{dede\:field name=[\'\"]?(\w+)[\'\"]?[^\}]+runphp[^\}]+\}(.+?)\{\/dede\:field(\.\\1)?\}/is' => array('_dede_php', -1),
            '/\{dede\:field\.([\w]+)[^\}]+runphp[^\}]+\}(.+?)\{\/dede\:field(\.\\1)?\}/is' => array('_dede_php', -1),
            //'/\{dede\:([^\}]+function[^\}]+)\}/is'	=> array('_dede_field', 1),
            '/\{dede\:([\w\.]+\s*name=[\'\"]?(\w+)[\'\"]?\s*(function)?[^\}]*)\}/is' => array('_dede_field', 1),
            '/\{dede\:(.+?)\}/is' => array('_dede_tag', -1),
            '/\[field\:(.+?)\/\]/' => array('_dede_field', 1),
            '/\{\/dede\:(\w+)\}/i' => array('_dede_tag_end', 1),
        );
        foreach ($dede_rules as $key => $value) {
            if (is_array($value)) {
                $GLOBALS['curval'] = $value;
                $string = preg_replace_callback($key, function($data){$value=$GLOBALS["curval"];$data = $value[1]>=0?$data[$value[1]]:$data;
				$callfunc = $value[0];
                return dede::$callfunc( $data );}, $string);
            } else {
                $string = preg_replace($key, $value, $string);
            }
        }
        return $string;
    }

    public static function _dede_field($string) {
        $string = trim($string, '/');
        $string = trim($string);
        preg_match('/([\w\.]+)(\s+function=(["\']?)(.+)\\3)/i', $string, $mt);

        $dede_tag_name = preg_replace('/(\s+|\.|\/).*/is', '', $string);
        //exit;

        if ($mt && count($mt) > 4) {
            $fieldname = $mt[1];
            if (preg_match('/(\w+)\.(\w+)/i', $fieldname, $m)) {
                if ($m[1] == 'global' || $m[1] == 'field') {
                    $fieldname = $m[2];
                } else {
                    $fieldname = '' . $m[1] . '[\'' . $m[2] . '\']';
                }
            }

            if (empty($mt[4])) {
                if (preg_match('/^\d/i', $fieldname)) {
                    return '';
                }
                return '<?php echo isset($' . $fieldname . ') ? $' . $fieldname . ' : \'\'; ?>';
            }
            $function = $mt[4];
            $function = str_replace('@me', '$' . $fieldname, $function);
            return '<?php $' . $fieldname . ' = isset($' . $fieldname . ') ? $' . $fieldname . ' : \'\'; echo ' . $function . '; ?>';
        } else if (preg_match('/name=(["\']?)(\w+)\\1[\s\w"\']+function=(["\']?)([^\\3]+)\\3/i', $string, $mt2)) {
            $fieldname = $mt2[2];
            $function = $mt2[4];
            if (preg_match('/^\d/i', $fieldname) || preg_match('/^\d/i', $function)) {
                return '';
            }
            $function = str_replace('@me', '$' . $fieldname, $function);
            return '<?php $' . $fieldname . ' = isset($' . $fieldname . ') ? $' . $fieldname . ' : \'\'; echo ' . $function . '; ?>';
        } else {
            if (preg_match('/name=(["\']?)(\w+)\\1/', $string, $m0)) {
                $fieldname = $m0[2];
                if (preg_match('/^\d/i', $fieldname)) {
                    return '';
                }
                return '<?php echo isset($' . $fieldname . ') ? $' . $fieldname . ' : ""; ?>';
            } else if (preg_match('/(\w+)\.(\w+)/i', $string, $m)) {
                if ($m[1] == 'global') {
                    $string = $m[2];
                } else {
                    $string = '' . $m[1] . '[\'' . $m[2] . '\']';
                }
            }
            if (preg_match('/^\d/i', $string)) {
                return '';
            }
            return '<?php echo isset($' . $string . ') ? $' . $string . ' : ""; ?>';
        }
    }

    public static function _dede_php($dede_tag_arr) {
        //dump($dede_tag_arr);
        if (is_string($dede_tag_arr)) {
            return '<?php ' . $dede_tag_arr . '; ?>';
        } else {
            $fieldname = $dede_tag_arr[1];
            //echo $fieldname;
            //exit;
            if (preg_match('/(\w+)\.(\w+)/i', $fieldname, $m)) {
                if ($m[1] == 'global') {
                    $fieldname = $m[2];
                } else {
                    $fieldname = '' . $m[1] . '[\'' . $m[2] . '\']';
                }
            }
            $phpscript = $dede_tag_arr[2];
            $phpscript = str_replace('@me', '$me', $phpscript);

            $prestring = "";
            if ($fieldname == 'array') {
                $prestring = '$me=$__value;';
            } else {
                $prestring = '$me=$' . $fieldname . ';';
            }

            return '<?php ' . $prestring . $phpscript . '; echo $me; ?>';
        }
    }

    public static function _dede_tag($dede_tag_arr) {
        global $dede_rules, $dede_replace;
        //dump($dede_tag_arr);
        $dede_tag = trim($dede_tag_arr[1]);

        $dede_tag_name = preg_replace('/(\s+|\.|\/).*/is', '', $dede_tag);

        /* if ($dede_tag_name=='arclist') {
          dump($dede_tag_arr);
          dump($dede_tag);
          } */


        if (!empty($dede_rules[$dede_tag_name]) && isset($dede_replace[$dede_tag_name])) {
            $key = $dede_rules[$dede_tag_name];
            $value = $dede_replace[$dede_tag_name];

            if (is_array($value)) {
                $GLOBALS["curvalue"] = $value;
                $dede_tag = preg_replace_callback($key, function($data){$value=$GLOBALS["curvalue"];$data = $value[1]>=0?$data[$value[1]]:$data;
				$callfunc = $value[0];
                return dede::$callfunc( $data );}, $dede_tag);
            } else {
                $dede_tag = preg_replace($key, $value, $dede_tag);
            }
            return $dede_tag;
        } else {
            return '';
        }
    }

    public static function _dede_tag_end($string) {
        global $dede_rules;
        $dede_tag = array_keys($dede_rules);

        if (in_array($string, $dede_tag)) {
            return '<!-- /foreach -->';
        } else {
            return '';
        }
    }

    /**/

    public static function field($string) {
        $string = trim($string);
        preg_match('/name=(["\']?)(\w+)\\1(\s+(function|runphp)=(["\']?)(.+)\\5)?/i', $string, $mt);
        preg_match('/\.(\w+)(\s+(function|runphp)=(["\']?)(.+)\\4)?/i', $string, $mt2);

        if ($mt) {
            $fieldname = $mt[2];

            if ($fieldname == 'imgurls') {
                return '<!--foreach $' . $fieldname . ' -->';
            }

            if (empty($mt[6])) {
                return '<?php echo isset($' . $fieldname . ') ? $' . $fieldname . ' : \'\'; ?>';
            }
            if ($mt[4] == 'function') {
                $function = $mt[6];
                $function = str_replace('@me', '$' . $fieldname, $function);
                return '<?php echo ' . $function . '; ?>';
            }
        } elseif ($mt2) {
            $fieldname = $mt2[1];
            if (empty($mt2[5])) {
                $str = '$' . $fieldname . '';
                return '<?php echo isset(' . $str . ') ? ' . $str . ' : \'{dede:field.' . $fieldname . '/}\'; ?>';
            }

            if ($mt2[3] == 'function') {
                $function = $mt2[5];
                $function = str_replace('@me', '$' . $fieldname . '', $function);
                return '<?php $' . $fieldname . ' = isset($' . $fieldname . ') ? $' . $fieldname . ' : \'\'; echo ' . $function . '; ?>';
            }
        } else {
            //$string = trim($string,'.');
            return '<?php echo $' . $string . '; ?>';
        }
    }

    /*     * ********************** 模板匹配结束 *************************** */

    public static function type($string = '') {
        $param_arr = getTagAttr($string);
        $addstr = '';
        if (empty($param_arr['typeid'])) {
            $addstr = '$arr["typeid"] = $typeid;';
        }
        return '<?php $arr = ' . var_export($param_arr, true) . '; ' . $addstr . ' $__type=get_type($arr);?><!-- foreach $__type -->';
    }

    public static function channel($string = '') {
        $param_arr = getTagAttr($string);
        unset($param_arr['currentstyle']);
        return '<?php $arr = ' . var_export($param_arr, true) . '; if(empty($arr["typeid"]) && isset($typeid)){$arr["typeid"] = $typeid;} $arr["current"] = $current; $_nav = get_nav($arr);?><!-- foreach $_nav -->';
    }

    public static function channelartlist($string = '') {
        $param_arr = getTagAttr($string);
        unset($param_arr['currentstyle']);
        return '<?php $arr = ' . var_export($param_arr, true) . '; $_nav = get_nav($arr);?><!-- foreach $_nav -->';
    }

    public static function arclist($data = array()) {
        $tagname = $data[1];
        $string = empty($data[2]) ? '' : $data[2];
        $string = trim($string);

        $param_arr = getTagAttr($string);

        if ($tagname == 'imglist' || $tagname == 'imginfolist') {
            $param_arr['listtype'] = 'image';
        } else if ($tagname == 'specart') {
            $param_arr['listtype'] = '';
        } else if ($tagname == 'coolart') {
            $param_arr['listtype'] = 'commend';
        } else {
            $param_arr['listtype'] = '';
        }

        $arr['tagname'] = $tagname;

        $col = empty($param_arr['col']) ? 1 : $param_arr['col'];

        $addstr = '';
        if (empty($param_arr['typeid'])) {
            $addstr = '$arr["typeid"] = $typeid;';
        }
        if (substr($string, -1) == '/') {  //以“/”结尾，标签自动闭合
            return '<?php
			$arr = ' . var_export($param_arr, true) . ';
			' . $addstr . '
			$__arclist=get_arclist($arr,"arclist");
			echo "<ul class=\"cl_' . $col . '\">\r\n";
			foreach($__arclist as $v) {
				echo "<li><a href=\"".$v["arcurl"]."\">".$v["title"]."</a><font>[".mydate("m-d H:i",$v["pubdate"])."]</font></li>";
			}
			echo "</ul>";
			?>';
        } else {
            return '<?php $arr = ' . var_export($param_arr, true) . '; ' . $addstr . ' $__arclist=get_arclist($arr,"arclist");?><!-- foreach $__arclist -->';
        }
    }

    public static function arclistsg($string = '') {
        return '<?php if(false){ ?>';
    }

    public static function _list($string = '') {
        $param_arr = getTagAttr($string);
        $param_arr['listtype'] = '';
        $addstr = '';
        if (empty($param_arr['typeid'])) {
            $addstr = '$arr["typeid"] = $current;';
        }
        if (M == 'tags') {
            $addstr .= '$arr["tagid"] = $tagid;';
        }
        if (M == 'plus' and A == 'search') {
            $addstr .= '$arr["keyword"] = $keyword;';
        }
        $param_arr['tagname'] = 'list';
        return '<?php $arr = ' . var_export($param_arr, true) . '; ' . $addstr . ' $__list = get_arclist($arr,"list"); ?><!-- foreach $__list -->';
    }

    public static function pagelist($string = '') {
        $param_arr = getTagAttr($string);
        return '<?php $arr = ' . var_export($param_arr, true) . '; $pagestr=get_pagelist($arr);?>{$pagestr}';
    }

    public static function pagebreak($string = '') {
        //dump($param_arr);exit;
        return '';
    }

    public static function prenext($string = '') {
        $param_arr = getTagAttr($string);
        dump($param_arr);exit;
        
        return '<?php $arr = ' . var_export($param_arr, true) . '; $__prenext = get_prenext($article_content, $arr); echo $__prenext; ?>';
    }

    public static function tag($string) {
        $param_arr = getTagAttr($string);

        //如果是自己闭合的标签直接构造HTML，否则返回数据数组
        if (strpos($string, '/') !== false) {
            return '<?php $arr = ' . var_export($param_arr, true) . '; $__tag = get_tag($arr, 1); echo $__tag; ?>';
        } else {
            return '<?php $arr = ' . var_export($param_arr, true) . '; $__tag = get_tag($arr); ?> <!-- foreach $__tag -->';
        }
    }

    public static function flinktype($string) {
        return '<?php $__flinktype[0] = array("id">0, "typeid"=>0,"typename"=>"友情链接"); ?><!-- foreach $__flinktype -->';
    }

    public static function _flink($string = '') {
        $param_arr = getTagAttr($string);
        //如果是自己闭合的标签直接构造HTML，否则返回数据数组
        if (strpos($string, '/') !== false) {
            return '<?php $arr = ' . var_export($param_arr, true) . '; $__flink = get_flink($arr, 1); echo $__flink; ?>';
        } else {
            return '<?php $arr = ' . var_export($param_arr, true) . '; $__flink = get_flink($arr, 0);?><!-- foreach $__flink -->';
        }
    }

    public static function adminname() {
        return '';
    }

    public static function infoguide($string = '') {
        $param_arr = getTagAttr($string);
        return '';
    }

    public static function infolink($string = '') {
        $param_arr = getTagAttr($string);
        //dump($param_arr);exit;
        return '';
    }

    public static function sql($string = '') {
        $sql = preg_replace('/\s*sql\s*=\s*([\'"])(.+?)\\1.*?/i', '$2', $string);
        return '<!-- sql ' . $sql . ' -->';
    }

    public static function loop($string = '') {
        $param_arr = array(
            'table' => '',
            'sort' => '',
            'row' => '10',
            'if' => '',
            'orderway' => 'desc',
        );
        $param_arr = getTagAttr($string, $param_arr);
        //dump($param_arr);exit;
        $table = $param_arr['table'];
        $where = empty($param_arr['if']) ? '' : 'where ' . $param_arr['if'];
        $limit = empty($param_arr['row']) ? '' : 'limit ' . $param_arr['row'];
        $sort = empty($param_arr['sort']) ? '' : 'order by ' . $param_arr['sort'] . ' ' . $param_arr['orderway'];
        $sql = "select * from {$table} {$where} {$sort} {$limit}";
        $sql = str_replace('"', "'", $sql);
        return '<!-- sql ' . $sql . ' -->';
    }

    //相关文章	
    public static function likearticle($string = '') {
        $string = trim($string);
        $param_arr = array(
            'row' => 10,
            'titlelen' => 30,
            'infolen' => 60,
            'mytypeid' => '',
            'imgwidth' => 120,
            'imgheight' => 90
        );
        $param_arr = getTagAttr($string, $param_arr);
        $col = empty($param_arr['col']) ? 1 : $param_arr['col'];

        $param_string = "'" . implode("', '", $param_arr) . "'";
        if (substr($string, -1) == '/') {  //以“/”结尾，标签自动闭合
            return '<?php $__likearticle=get_likearticle($article_content,' . $param_string . ');
			echo "<ul class=\"cl_' . $col . '\">\r\n";
			foreach($__arclist as $v) {
				echo "<li><a href=\"".$v["arcurl"]."\">".$v["title"]."</a><font>[".mydate("m-d H:i",$v["pubdate"])."]</font></li>";
			}
			echo "</ul>";
			?>';
        } else {
            return '<?php $__likearticle=get_likearticle($article_content,' . $param_string . ');?><!-- foreach $__likearticle -->';
        }
    }

}
